<template>
  <div class="create-post-container">
    <!-- 基础信息抽屉 -->
    <a-drawer
      :width="400"
      :visible="visible"
      title="帖子基础信息"
      :footer="false"
      @cancel="handleCloseDrawer"
    >
      <a-form ref="formRef" :model="post" layout="vertical" class="post-form">
        <a-form-item
          field="title"
          label="帖子标题"
          :rules="[
            {
              required: true,
              message: '请输入标题'
            }
          ]"
        >
          <a-input v-model="post.title" placeholder="请输入标题" size="large" allow-clear @input="handleTitleInput" />
        </a-form-item>
        <a-form-item
          field="zone"
          label="帖子分区"
          :rules="[
            {
              required: true,
              message: '请选择分区'
            }
          ]"
        >
          <a-select
            v-model="post.zone"
            placeholder="请选择分区"
            allow-clear
            :options="zoneOptions"
            size="large"
          ></a-select>
        </a-form-item>
        <a-form-item
          field="tags"
          label="帖子标签"
          :rules="[
            {
              required: true,
              message: '请至少添加一个标签'
            }
          ]"
        >
          <a-input-tag
            v-model="post.tags"
            allow-clear
            placeholder="请输入标签并回车"
            size="large"
            @input="handleTagsInput"
          />
        </a-form-item>
        <div class="drawer-footer">
          <a-button type="primary" size="large" @click="handleCloseDrawer">确定</a-button>
        </div>
      </a-form>
    </a-drawer>

    <!-- 编辑器工具栏 -->
    <div class="editor-toolbar">
      <div class="editor-info">
        <h2 class="editor-title">{{ post.title || '创建新帖子' }}</h2>
        <div class="editor-metadata" v-if="post.zone || (post.tags && post.tags.length > 0)">
          <a-tag color="blue" v-if="post.zone" class="zone-tag">
            {{ getZoneLabel(post.zone) }}
          </a-tag>
          <a-space class="tag-list">
            <a-tag
              v-for="(tag, index) in post.tags"
              :key="index"
              :color="getTagColor(index)"
            >
              {{ tag }}
            </a-tag>
          </a-space>
        </div>
      </div>
      <a-space>
        <a-popconfirm content="确定要发布吗？" @ok="handleSubmit">
          <a-button type="primary" size="large" class="publish-button">
            <template #icon>
              <icon-share-internal />
            </template>
            发布帖子
          </a-button>
        </a-popconfirm>
        <a-button type="outline" size="large" class="info-button" @click="handleOpenDrawer">
          <template #icon>
            <icon-edit />
          </template>
          编辑信息
        </a-button>
      </a-space>
    </div>

    <!-- Markdown编辑器 -->
    <div class="editor-wrapper">
      <MdEditor
        v-model="post.content"
        placeholder="请输入内容（支持 Markdown）"
        :preview="true"
        :auto-detect-code="true"
        theme="light"
        @onUploadImg="onUploadImg"
        @onChange="handleMdChange"
        class="md-editor"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { OjPostAddRequest } from '@/api/gen-api';
import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { OjPostService } from '@/api/gen-api/services/OjPostService.ts';
import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const formRef = ref();
const zoneOptions = ref<SelectOptionData[]>([
  {
    label: '综合',
    value: 'synthesis'
  },
  {
    label: '题目讨论',
    value: 'frontend'
  },
  {
    label: '学习分享',
    value: 'backend'
  },
  {
    label: '技术交流',
    value: 'harmony'
  },
  {
    label: '系统反馈',
    value: 'aigc'
  }
]);

// 为标签生成不同颜色
const tagColors = ['blue', 'green', 'orange', 'purple', 'cyan', 'red', 'gray'];
const getTagColor = (index: number) => {
  return tagColors[index % tagColors.length];
};

// 获取分区名称
const getZoneLabel = (zoneValue: string) => {
  const zone = zoneOptions.value.find(item => item.value === zoneValue);
  return zone ? zone.label : '综合';
};

const post = ref<OjPostAddRequest>({
  title: '',
  content: '',
  tags: [],
  zone: ''
});

const visible = ref(false);

const handleOpenDrawer = () => {
  visible.value = true;
};

const handleCloseDrawer = () => {
  // 在关闭抽屉前检查并过滤敏感词
  post.value.title = filterSensitiveWords(post.value.title);
  if (Array.isArray(post.value.tags)) {
    post.value.tags = post.value.tags.map(tag => filterSensitiveWords(tag));
  }

  visible.value = false;
};

const handleSubmit = () => {
  // 过滤表单中所有的敏感词
  post.value.title = filterSensitiveWords(post.value.title);
  post.value.content = filterSensitiveWords(post.value.content);
  post.value.tags = post.value.tags.map(tag => filterSensitiveWords(tag));

  if (!post.value.title) {
    Message.warning('请先设置帖子标题');
    handleOpenDrawer();
    return;
  }

  if (!post.value.zone) {
    Message.warning('请先选择帖子分区');
    handleOpenDrawer();
    return;
  }

  if (!post.value.tags || post.value.tags.length === 0) {
    Message.warning('请至少添加一个标签');
    handleOpenDrawer();
    return;
  }

  if (!post.value.content) {
    Message.warning('帖子内容不能为空');
    return;
  }

  OjPostService.save(post.value).then(res => {
    if (res.result) {
      Message.success('发布成功');
      // 可以添加发布成功后的导航
      router.push({
        name: 'Post'
      });
    }
  }).catch(err => {
    Message.error('发布失败：' + (err.message || '未知错误'));
  });
};

// 图片上传方法
const onUploadImg = async (files, callback) => {
  // 这里是示例，实际实现可能需要调用后端上传API
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = () => {
          resolve(reader.result);
        };
        reader.readAsDataURL(file);
      });
    })
  );
  callback(res);
};

// 敏感词列表
const sensitiveWords = [
  '傻逼', '操你妈', '滚蛋', '废物', '垃圾', '混蛋', '王八蛋', '白痴', '笨蛋',
  '狗屎', '贱人', '妈的', '他妈的', '草你', '艹', 'fuck', 'shit', 'bitch', 'damn',
  // 可以根据需要添加更多敏感词
];

// 敏感词过滤函数 - 增强版
const filterSensitiveWords = (text) => {
  if (!text) return text;

  let filteredText = text;
  let hasSensitiveWord = false;

  // 检查并替换所有敏感词
  sensitiveWords.forEach(word => {
    // 创建包含各种变形的正则表达式 (处理中间加空格、特殊符号或数字等干扰)
    // 例如："傻 逼"，"傻_逼"，"傻.逼" 等都能被检测到
    const escapedWord = word.split('').join('[\\s_\\-.*0-9]*');
    const regex = new RegExp(escapedWord, 'gi');

    if (regex.test(filteredText)) {
      hasSensitiveWord = true;
      // 将敏感词替换为相同长度的星号
      filteredText = filteredText.replace(regex, match => '*'.repeat(match.length));
    }

    // 再次检查原始敏感词（无变形）
    if (filteredText.includes(word)) {
      hasSensitiveWord = true;
      const replacement = '*'.repeat(word.length);
      const simpleRegex = new RegExp(word, 'gi');
      filteredText = filteredText.replace(simpleRegex, replacement);
    }
  });

  // 如果发现敏感词，显示提示
  if (hasSensitiveWord) {
    Message.warning('请礼貌用语');
  }

  return filteredText;
};

// 监听标题输入
const handleTitleInput = (value) => {
  const filteredTitle = filterSensitiveWords(value);
  if (filteredTitle !== value) {
    post.value.title = filteredTitle;
  }
};

// 监听标签输入
const handleTagsInput = (tags) => {
  if (!Array.isArray(tags)) return tags;

  const filteredTags = tags.map(tag => filterSensitiveWords(tag));
  // 检查是否有过滤后的标签与原标签不同
  const hasSensitiveTag = tags.some((tag, index) => tag !== filteredTags[index]);

  if (hasSensitiveTag) {
    post.value.tags = filteredTags;
  }

  return filteredTags;
};

// 处理Markdown编辑器内容变化
const handleMdChange = (content) => {
  const filteredContent = filterSensitiveWords(content);
  if (filteredContent !== content) {
    // 由于 v-model 双向绑定的特性，需要在下一个事件循环中执行以避免冲突
    setTimeout(() => {
      post.value.content = filteredContent;
    }, 0);
  }
};

// 添加监听
watch(() => post.value.title, handleTitleInput);
watch(() => post.value.tags, handleTagsInput, { deep: true });
watch(() => post.value.content, handleMdChange);
</script>

<style scoped lang="less">
.create-post-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 140px);
  background-color: var(--color-bg-1);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: white;
  border-bottom: 1px solid var(--color-border-2);
  border-radius: 8px 8px 0 0;

  .editor-info {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .editor-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--color-text-1);
    }

    .editor-metadata {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;

      .zone-tag {
        margin-right: 8px;
      }

      .tag-list {
        margin-top: 4px;

        :deep(.arco-tag) {
          margin-right: 4px;
          margin-bottom: 4px;
          border-radius: 3px;
        }
      }
    }
  }

  .publish-button {
    background-color: #2759CD;
    border-color: #2759CD;
    transition: all 0.3s;

    &:hover {
      background-color: #3769dd;
      border-color: #3769dd;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(39, 89, 205, 0.2);
    }
  }

  .info-button {
    color: #2759CD;
    border-color: #2759CD;
    transition: all 0.3s;

    &:hover {
      background-color: rgba(39, 89, 205, 0.05);
      transform: translateY(-2px);
    }
  }
}

.editor-wrapper {
  flex: 1;
  overflow: hidden;
  padding: 0;
  background-color: white;
  border-radius: 0 0 8px 8px;

  .md-editor {
    height: 100%;
    border: none;
    border-radius: 0;
  }

  :deep(.md-editor-toolbar) {
    border-bottom: 1px solid var(--color-border-2);
  }
}

.post-form {
  padding: 10px 0;

  :deep(.arco-form-item-label) {
    font-weight: 500;
  }

  :deep(.arco-input:focus),
  :deep(.arco-select:focus-within),
  :deep(.arco-input-tag:focus-within) {
    border-color: #2759CD;
  }
}

.drawer-footer {
  margin-top: 24px;
  text-align: right;

  :deep(.arco-btn-primary) {
    background-color: #2759CD;
    border-color: #2759CD;
    transition: all 0.3s;

    &:hover {
      background-color: #3769dd;
      border-color: #3769dd;
      box-shadow: 0 4px 12px rgba(39, 89, 205, 0.2);
    }
  }
}

:deep(.arco-drawer-header) {
  border-bottom: 1px solid var(--color-border-2);
}

:deep(.arco-drawer-header-title) {
  color: #2759CD;
  font-weight: 600;
}
</style>
